const Question = require('../models/questions')

class Questions {
  async find(ctx) {
    // 每页大小
    const pageSize = Math.max((ctx.query.page_size || 10) * 1, 1)
    // 当前页
    const current = ctx.query.current * 1
    // 偏移量
    const offset = Math.max(current - 1, 0) * pageSize
    // 查询参数
    const reg = new RegExp(ctx.query.q)
    // NOTE: $or 表示二者之一
    const params = { $or: [{ title: reg }, { description: reg }] }

    ctx.body = await Question.find(params).limit(pageSize).skip(offset)
  }

  async findById(ctx) {
    const { fields = '' } = ctx.query
    // example: name;avatar_url;introducation ---> name avatar_url introducation
    const str = fields.replaceAll(';', ' ')
    const question = await Question.findById(ctx.params.id)
      .select(str)
      .populate('questioner topics')
    ctx.body = question
  }

  async create(ctx) {
    ctx.verifyParams({
      title: { type: 'string', required: true },
      description: { type: 'string', required: false }
    })
    const params = { ...ctx.request.body, questioner: ctx.state.user._id }
    const question = await new Question(params).save()
    ctx.body = question
  }

  async update(ctx) {
    ctx.verifyParams({
      title: { type: 'string', required: false },
      description: { type: 'string', required: false }
    })
    const question = await Question.findByIdAndUpdate(
      ctx.params.id,
      ctx.request.body,
      {
        new: true
      }
    )
    ctx.body = question
  }

  async delete(ctx) {
    await Question.findOneAndDelete(ctx.params.id)
    ctx.status = 204
  }
}

module.exports = new Questions()
